<?php

namespace App\Http\Services\Admin;

use App\Http\Services\Service;
use App\Models\Admin\MenuModel;
use App\Utils\Arr;
use Illuminate\Support\Facades\Cache;

class MenuService implements Service
{
    public function tree(): array
    {
        return Arr::List2Tree($this->index());
    }

    public function index(array $params = [], array $columns = ['*']): array
    {
        return MenuModel::all($columns)->where('disable', 0)->toArray();
    }

    public function insertOrUpdate(int $id, array $data): array
    {
        if ($id) {
            MenuModel::query()->where('id', $id)->update(Arr::key0Snake($data));
        } else {
            $id = MenuModel::query()->insertGetId(Arr::key0Snake($data));
        }
        $data['id'] = $id;
        return $data;
    }

    public function delete(int $id)
    {
        MenuModel::query()->where('id', $id)->delete();
    }

    public function getCacheTreeByRoles(array $roles): array
    {
        $tempKey = [];
        $temp = [];
        foreach ($roles as $id) {
            $key = 'menu:' . $id;
            if (Cache::has($key)) {
                $menu = Cache::get($key);
            } else {
                $menu = $this->getListByRole($id);
                Cache::put($key, $menu);
            }
            foreach ($menu as $mn) {
                if (in_array($mn['id'], $tempKey)) {
                    continue;
                }
                $tempKey[] = $mn['id'];
                $temp[] = $mn;
            }
        }
        return Arr::List2Tree($temp);
    }

    public function disableMenuCacheByRole(int $roleId): void
    {
        Cache::forget('menu:' . $roleId);
    }

    public function getListByRole(int $roleId): array
    {
        return MenuModel::byRoleId($roleId)->get()->toArray();
    }
}
